package com.atguigu.campusintelligentassistantsystem.controller;

import com.atguigu.campusintelligentassistantsystem.entity.AiChatRecord;
import com.atguigu.campusintelligentassistantsystem.service.AiChatService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/ai")
@CrossOrigin(origins = "*")
public class AiController {

    @Autowired
    private AiChatService aiChatService;

    /**
     * AI问答接口
     * @param userId 用户ID
     * @param question 用户问题
     * @return AI回答
     */
    @PostMapping("/ask")
    public ResponseEntity<String> ask(@RequestParam Long userId, @RequestParam String question) {
        try {
            String answer = aiChatService.processQuestion(userId, question);
            return ResponseEntity.ok(answer);
        } catch (Exception e) {
            return ResponseEntity.status(500).body("AI服务异常: " + e.getMessage());
        }
    }

    /**
     * 获取聊天历史记录
     * @param userId 用户ID
     * @return 聊天记录列表
     */
    @GetMapping("/history/{userId}")
    public ResponseEntity<List<AiChatRecord>> getHistory(@PathVariable Long userId) {
        try {
            List<AiChatRecord> history = aiChatService.getChatHistory(userId);
            return ResponseEntity.ok(history);
        } catch (Exception e) {
            return ResponseEntity.status(500).build();
        }
    }

    /**
     * 删除聊天记录
     * @param id 记录ID
     * @return 操作结果
     */
    @DeleteMapping("/history/{id}")
    public ResponseEntity<String> deleteHistory(@PathVariable Long id) {
        try {
            aiChatService.deleteChatRecord(id);
            return ResponseEntity.ok("删除成功");
        } catch (Exception e) {
            return ResponseEntity.status(500).body("删除失败: " + e.getMessage());
        }
    }

    /**
     * 生成学习资料
     * @param userId 用户ID
     * @param demand 学习需求
     * @return 生成的学习资料
     */
    @PostMapping("/study-material")
    public ResponseEntity<String> generateStudyMaterial(@RequestParam Long userId, @RequestParam String demand) {
        try {
            // 这里可以添加保存学习资料生成记录的逻辑
            String material = aiChatService.processQuestion(userId, "请生成关于\"" + demand + "\"的学习资料");
            return ResponseEntity.ok(material);
        } catch (Exception e) {
            return ResponseEntity.status(500).body("学习资料生成失败: " + e.getMessage());
        }
    }
}